package com.hellowx.qydcdev.controller;

import com.hellowx.qydcdev.annotaion.RequiredToken;
import com.hellowx.qydcdev.entity.BusinessVO;
import com.hellowx.qydcdev.entity.LoginVO;
import com.hellowx.qydcdev.entity.User;
import com.hellowx.qydcdev.service.BusinessService;
import com.hellowx.qydcdev.service.UserService;
import com.hellowx.qydcdev.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created on 2022/1/11.
 *
 * @author Hello WX
 */

@Api(tags = "后台用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private BusinessService businessService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody LoginVO loginVO){
        User user = new User();
        user.setPassword(loginVO.getPassword());
        user.setPhone(loginVO.getPhone());
        String token = userService.login(user);
        return ResponseEntity.ok(token);
    }

    @ApiOperation("添加用户")
    @PostMapping("/save")
    @RequiredToken
    public ResponseEntity<String> saveUser(@RequestBody User user){
        String msg = userService.saveUser(user);
        return ResponseEntity.ok(msg);
    }

    @ApiOperation("重置密码")
    @PostMapping("/resetPwd")
    @RequiredToken
    public ResponseEntity<String> resetPwd(@RequestParam("userId") Long userId){
        userService.resetPwd(userId);
        return ResponseEntity.ok("密码重置完成");
    }

    @ApiOperation("获取登录用户信息")
    @GetMapping("/getUser")
    @RequiredToken
    public ResponseEntity<User> getUser(HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        return ResponseEntity.ok(loginUser);
    }

    @ApiOperation("获取店铺信息")
    @GetMapping("/getBusiness")
    @RequiredToken
    public ResponseEntity<BusinessVO> getBusinessByUserId(HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        BusinessVO businessVO = businessService.getByIdIncludeUser(loginUser.getBusinessId());
        return ResponseEntity.ok(businessVO);
    }

    @ApiOperation("更新密码")
    @PostMapping("/updatePassword")
    @RequiredToken
    public ResponseEntity<String> updatePassword(@RequestParam("newPassword") String newPassword,
                                                 HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        User user = new User();
        user.setId(loginUser.getId());
        user.setPassword(MD5Utils.generatePwd(newPassword));
        String msg = userService.updatePassword(user);
        return ResponseEntity.ok(msg);
    }
}
